package com.lnu_devteam.zongce.interceptor;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.lnu_devteam.zongce.annotation.AuthCheck;
import com.lnu_devteam.zongce.common.ErrorCode;
import com.lnu_devteam.zongce.exception.BusinessException;
import com.lnu_devteam.zongce.model.entity.User;
import com.lnu_devteam.zongce.model.enums.RoleEnum;
import com.lnu_devteam.zongce.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author xbaozi
 * @version 1.0
 * @className AuthCheck
 * @date 2022-12-14  14:46
 * @description 权限校验 AOP
 */
@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    /**
     * 执行拦截
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        List<RoleEnum> anyRole = Arrays.stream(authCheck.anyRole())
                .filter(ObjectUtils::isNotNull)
                .collect(Collectors.toList());
        RoleEnum mustRole = authCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 当前登录用户
        User user = userService.getLoginUser(request);
        if (user == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 拥有任意权限即通过
        if (CollectionUtils.isNotEmpty(anyRole)) {
            Integer auth = user.getUAuth();
            RoleEnum userRole = RoleEnum.getRollByAuth(auth);
            if (!anyRole.contains(userRole)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
        // 必须有所有权限才通过
        if (ObjectUtils.isNotNull(mustRole)) {
            Integer auth = user.getUAuth();
            RoleEnum userRole = RoleEnum.getRollByAuth(auth);
            if (auth.compareTo(mustRole.getAuth()) < 0) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
        // 通过权限校验，放行
        return joinPoint.proceed();
    }
}

